package com.ruoyi.goods.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.vo.GoodsOrderQueryVo;
import com.ruoyi.common.vo.GoodsOrderSendVo;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.GoodsOrder;
import com.ruoyi.system.domain.WxUser;
import com.ruoyi.system.domain.vo.GoodsOrderUpdateVo;
import com.ruoyi.system.domain.vo.GoodsOrderVo;
import com.ruoyi.system.service.GoodsOrderService;
import com.ruoyi.system.service.WxUserService;
import com.ruoyi.wx.pojo.vo.SendCommonTemplateVo;
import com.ruoyi.wx.service.WxMessageService;
import com.ruoyi.wx.utils.WxMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class GoodsOrderController {
    @Autowired
    private GoodsOrderService goodsOrderService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private WxMessageService wxMessageService;
    @Autowired
    private WxUserService wxUserService;

    /**
     * 用户获取订单列表
     *
     * @param current 页码
     */
    @PostMapping("/list/{current}")
    public AjaxResult getGoodsOrderList(@PathVariable("current") int current,
                                        @RequestBody(required = false) GoodsOrderQueryVo goodsOrderQueryVo) {
        PageHelper.startPage(current, 10);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<GoodsOrder> goodsChoices = goodsOrderService.queryAllByLimit(loginUser, goodsOrderQueryVo.getStatus());
        return AjaxResult.success(PageInfo.of(goodsChoices));
    }

    /**
     * 管理员获取订单列表
     *
     * @param current 页码
     */
    @GetMapping("/admin/list/{current}")
    public AjaxResult adminQueryAllByLimit(@PathVariable("current") int current,
                                           @RequestParam(required = false, defaultValue = "") String status,
                                           @RequestParam(required = false, defaultValue = "") String phone,
                                           @RequestParam(required = false, defaultValue = "") String title) {
        PageHelper.startPage(current, 10);
        List<GoodsOrderVo> goodsChoices = goodsOrderService.adminQueryAllByLimit(status, phone, title);
        return AjaxResult.success(PageInfo.of(goodsChoices));
    }

    /**
     * 更新
     *
     * @param goodsOrderUpdateVo 更新数据
     */
    @PostMapping("/update")
    public AjaxResult updateGoodsOrder(@RequestBody GoodsOrderUpdateVo goodsOrderUpdateVo) {
        // 0：待审核，1：待发货，2：待收货，3：已完成，4：已关闭，5：待提交，6：已提交
        if ("3".equalsIgnoreCase(goodsOrderUpdateVo.getGoodsOrder().getStatus())) {
            GoodsOrder goodsOrder = goodsOrderService.queryById(goodsOrderUpdateVo.getGoodsOrder().getId());
            if (goodsOrder != null) {
                WxUser wxUser = wxUserService.queryById(Integer.parseInt(goodsOrder.getUserId()));
                this.faSongXiaoXiGeiDaRenHuoZheYongHu("【" + goodsOrder.getTitle() + "】此带货任务已经完成，感谢您的支持",
                        wxUser.getOpenId(),
                        "如需更多带货机会可咨询客服，微信号：kelebdd", "已完成");
            }
        }
        GoodsOrder update = goodsOrderService.update(goodsOrderUpdateVo);
        if (update == null) return AjaxResult.error("失败(销量为空/商品下架)!");
        return AjaxResult.success();
    }

    /**
     * 创建订单
     *
     * @param goodsOrder 添加数据
     */
    @PostMapping("/save")
    public AjaxResult saveGoodsOrder(@RequestBody GoodsOrder goodsOrder) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        WxUser wxUser = wxUserService.queryById(Integer.parseInt(loginUser.getUser().getUserId().toString()));
        this.faSongXiaoXiGeiDaRenHuoZheYongHu("【" + goodsOrder.getTitle() + "】申请样品成功，等待商家审核。",
                wxUser.getOpenId(),
                "请耐心等待商家审核，如有疑问可咨询客服，微信号：kelebdd", "待审核");
        goodsOrderService.insert(goodsOrder, loginUser);
        return AjaxResult.success();
    }

    /**
     * 根据ID删除数据
     *
     * @param id id
     */
    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteGoodsOrder(@PathVariable("id") int id) {
        goodsOrderService.deleteById(id);
        return AjaxResult.success();
    }

    @PostMapping("send")
    public AjaxResult orderSendGoods(@RequestBody GoodsOrderSendVo goodsOrderSendVo) {
        goodsOrderService.orderSendGoods(goodsOrderSendVo);
        GoodsOrder goodsOrder = goodsOrderService.queryById(Integer.parseInt(goodsOrderSendVo.getOrder()));
        if (goodsOrder != null) {
            WxUser wxUser = wxUserService.queryById(Integer.parseInt(goodsOrder.getUserId()));
            this.faSongXiaoXiGeiDaRenHuoZheYongHu("【" + goodsOrder.getTitle() + "】样品已经发货，快递公司：" + goodsOrderSendVo.getLogisticsName() + "，快递单号：" + goodsOrderSendVo.getLogisticsNum() + "，请注意查收。"
                    , wxUser.getOpenId(),
                    "如有疑问可咨询客服，微信号：kelebdd", "已发货");
        }
        return AjaxResult.success();
    }

    /***
     * 通过商家id获取订单信息
     * @param current
     * @return
     */
    @PostMapping("/getOrderInfoByUserId/{current}")
    public AjaxResult getOrderInfoByUserId(@PathVariable("current") int current,
                                           @RequestBody GoodsOrder goodsOrder) {
        PageHelper.startPage(current, 10);
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long merchantId = loginUser.getUser().getUserId();
        List<GoodsOrder> goodsOrders = goodsOrderService.getOrderInfoByUserId(String.valueOf(merchantId), goodsOrder);
        return AjaxResult.success(PageInfo.of(goodsOrders));
    }

    @PostMapping("/commitwork")
    public AjaxResult commitWork(String orderId, String content) {
        goodsOrderService.commitWork(orderId, content);
        GoodsOrder goodsOrder = goodsOrderService.queryById(Integer.parseInt(orderId));
        if (goodsOrder != null) {
            WxUser wxUserSangjia = wxUserService.queryById(Integer.parseInt(goodsOrder.getMerchantId()));
            this.faSongXiaoXiGeiDaRenHuoZheYongHu("【" + goodsOrder.getTitle() + "】您已经成功提交作业，等待商家审核。"
                    , wxUserSangjia.getOpenId(),
                    "请在72小时内尽快审核，超时将自动审核通过，如有疑问可咨询客服，微信号：kelebdd", "已提交，待商家审核");
            WxUser wxUserDaren = wxUserService.queryById(Integer.parseInt(goodsOrder.getUserId()));
            this.faSongXiaoXiGeiDaRenHuoZheYongHu("【" + goodsOrder.getTitle() + "】达人已提交带货作业，请尽快审核。"
                    , wxUserDaren.getOpenId(),
                    "72小时内审核完毕，如需更多带货机会可咨询客服，微信号：kelebdd", "已提交，待商家审核");
        }
        return AjaxResult.success();
    }

    private boolean faSongXiaoXiGeiDaRenHuoZheYongHu(String title, String openId, String content, String status) {
        SendCommonTemplateVo commonTemplateMessage = WxMessageUtils.getCommonTemplateMessage(openId, content, title, status);
        return wxMessageService.sendCommonTemplateMessage(commonTemplateMessage);
    }
}
